import { getLogger } from '@gnlab/utils'
import { Result, Button } from 'antd'
import { Component } from 'react'

const logger = getLogger('ui/catch-error')

export class ErrorBoundary extends Component<{
  message?: React.ReactNode
  className?: string
  children: React.ReactNode
}> {
  state = {
    error: null as string | null,
  }

  static getDerivedStateFromError(error: Error) {
    return { error: String(error) }
  }

  componentDidCatch(error: Error) {
    logger.error(error)
  }

  render() {
    function refresh() {
      location.reload()
    }

    if (this.state.error !== null) {
      return <div css={{ marginTop: '5vh' }}>
        <Result
          status="error"
          title="页面错误"
          subTitle={this.state.error}
          extra={[
            <Button key="refresh" onClick={refresh}>
              刷新页面
            </Button>,
          ]}
        />
      </div>
    }
    return this.props.children
  }
}
